package com.company.manage.system.service;

import com.company.manage.common.base.BaseService;
import com.company.manage.common.persistence.HibernateDao;
import com.company.manage.system.dao.RolePermissionDao;
import com.company.manage.system.entity.Permission;
import com.company.manage.system.entity.Role;
import com.company.manage.system.entity.RolePermission;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by HuangYong on 2016/1/23.
 * desc:角色权限service
 */
@Service
@Transactional(readOnly = true)
public class RolePermissionService extends BaseService<RolePermission, Integer> {
    private static final String TAG = "RolePermissionService";

    @Autowired
    private RolePermissionDao rolePermissionDao;

    @Override
    public HibernateDao<RolePermission, Integer> getEntityDao() {
        return rolePermissionDao;
    }

    /**
     * 获取角色具有的权限的id
     *
     * @param roleId
     * @return
     */
    public List<Integer> getPermissionIds(Integer roleId) {
        return rolePermissionDao.findPermissionIds(roleId);
    }

    public void updateRolePermission(Integer roleId, List<Integer> oldList, List<Integer> newList) {
        /*删除旧的角色权限关系*/
        for (int i = 0; i < oldList.size(); i++) {
            if (!newList.contains(oldList.get(i))) {
                rolePermissionDao.deleteRolePermission(roleId, oldList.get(i));
            }
        }
        /*创建新的角色权限关系*/
        for (int i = 0; i < newList.size(); i++) {
            if (!oldList.contains(newList.get(i))) {
                rolePermissionDao.save(getRolePermission(roleId, newList.get(i)));
            }
        }
    }

    /**
     * 封装角色权限对象
     *
     * @param roleId       角色id
     * @param permissionId 权限id
     * @return
     */
    private RolePermission getRolePermission(Integer roleId, Integer permissionId) {
        RolePermission rolePermission = new RolePermission();
        rolePermission.setRole(new Role(roleId));
        rolePermission.setPermission(new Permission(permissionId));
        return rolePermission;
    }

    /**
     * 清空该角色用户的权限缓存
     * @param pc
     */
    public void clearUserPermissionCache(PrincipalCollection pc){
        RealmSecurityManager securityManager = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        UserAuthorizingRealm userRealm = (UserAuthorizingRealm)securityManager.getRealms().iterator().next();
        userRealm.clearCachedAuthorizationInfo(pc);
    }

}